//
//  ConnectRequest.m
//  SweetComics
//
//  Created by LeeZhe on 15/1/29.
//  Copyright (c) 2015年 LeeZhe. All rights reserved.
//

#import "ConnectRequest.h"

@implementation ConnectRequest
+ (void)getConnect:(NSString *)url block:(void (^)(NSData *))block
{
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *urls = [NSURL URLWithString:url];
    
    // 创建请求对象
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urls cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
    request.HTTPMethod = @"Get";
    
    // 连接服务器
    
     [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
         NSString *docpath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
         
         NSString *path = [NSString stringWithFormat:@"%@/%ld",docpath,[url hash]];
         if (data != nil) {
             BOOL result = [NSKeyedArchiver archivedDataWithRootObject:data];
             NSLog(@"seve succed : %d",result);
             block(data);
             
         }
         else
         {
             NSData *picData = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
             if (picData != nil) {
                 block(picData);
             }
         }
         
     }];
    
    
    
}
@end
